package com.web.action;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.StringUtils;
import com.web.action.res.LatestCathecticResponse;
import com.web.action.res.Response;
import com.web.common.Sys;
import com.web.model.TCathectic;
import com.web.model.TDict;
import com.web.model.TUser;
import com.web.model.TUserBalanceRecord;
import com.web.model.constant.Constant;
import com.web.service.TCathecticService;
import com.web.service.TDictService;
import com.web.service.TUserBalanceRecordService;
import com.web.service.TUserService;
import com.web.utils.MakeOrderNum;
import com.web.utils.WebUtil;

/**
 * 投注相关
 * 
 * @author yzy
 *
 */
@Controller
@RequestMapping("cathectic")
public class TCathecticController {
	@Autowired
	private TCathecticService catecticService;

	@Autowired
	private TUserService userService;

	@Resource(name = "sys")
	private Sys sys;

	@Autowired
	private TDictService dictService;

	@Autowired
	private TUserBalanceRecordService userBalanceRecordService;

	private static SimpleDateFormat dayFmarter = new SimpleDateFormat("yyyy-MM-dd");

	/* 投注 */
	@RequestMapping(value = "", method = RequestMethod.POST)
	@ResponseBody
	public Response cathectic(HttpServletRequest request, HttpSession session) {
		Response res = new Response();
		// 判定是否封盘
		if (sys.getLockTime() < System.currentTimeMillis()) {
			return res.Lockd;
		}
		String catecticArr = request.getParameter("catecticArr");
		// 登录校验
		TUser u = (TUser) request.getSession().getAttribute(Constant.SESSION_USER);
		if (u == null) { // 用户未登录
			return res.TokenInvalid;
		}
		if (u.getRoleId().longValue() != 3) { // 会员才能投注
			return res.VIP;
		}
		// 参数判空
		if (StringUtils.isNullOrEmpty(catecticArr)) {
			return res.ParamError;
		}

		try {
			JSONArray catecticJsonArray = JSONArray.parseArray(catecticArr);
			if (catecticJsonArray == null || catecticJsonArray.size() == 0) {
				return res.ParamError;
			}
			int sumPrice = 0;
			List<TCathectic> insertCathecticList = new ArrayList<TCathectic>();
			List<TUserBalanceRecord> userbalanceRecords = new ArrayList<TUserBalanceRecord>();
			TUserBalanceRecord ubr = null;
			for (int i = 0; i < catecticJsonArray.size(); i++) {
				TCathectic c = JSONObject.toJavaObject(catecticJsonArray.getJSONObject(i), TCathectic.class);
				TDict d = sys.getDict(c.getCathecticType() + "-" + c.getCathecticCode());
				c.setTermCd(sys.getNextTermcd());
				c.setWinAmt(d.getDictRate() * c.getCathecticInt());
				c.setCreateUser(u.getUserId());
				c.setCathecticIp(WebUtil.getRealIp(request));
				c.setCathecticNum(MakeOrderNum.makeOrderNum());
				c.setCreateTime(new Date());
				c.setIsWin("0");
				c.setDictRate(d.getDictRate());
				insertCathecticList.add(c);
				sumPrice += c.getCathecticInt();

				/** **********资金记录************* */
				ubr = new TUserBalanceRecord();
				ubr.setUserId(u.getUserId());
				ubr.setBalance(0.0 - c.getCathecticInt());
				ubr.setBalanceContext(
						sys.getBuyBalanceContext(1, sys.getNextTermcd(), d.getDictType(), d.getDictCode()));
				ubr.setBalanceType(Constant.USER_BALANCE_TYPE_2);
				ubr.setBalanceDate(new Date());
				userbalanceRecords.add(ubr);
			}

			// 校验账户余额
			TUser user = userService.selectByPrimaryKey(u.getUserId());
			if (sumPrice > user.getUserBalance()) { // 账户余额不足
				return res.UserBalanceInsufficient;
			}
			catecticService.insertList(insertCathecticList);
			userBalanceRecordService.insertList(userbalanceRecords);
			/** *****扣减账户余额******* */
			user.setUserBalance(user.getUserBalance() - sumPrice);
			user.setPassword(null);
			userService.updateByPrimaryKey(user);
			user.setUserBalance(WebUtil.formartDouble(user.getUserBalance(), 2));
			user.setCreditAmt(WebUtil.formartDouble(user.getCreditAmt(), 2));
			session.setAttribute(Constant.SESSION_USER, user);
			return res.SUCC;
		} catch (Exception e) {
			e.printStackTrace();
			return res.Error_Network;
		}
	}

	/* 当期下注情况 */
	@RequestMapping(value = "latest_cathectic", method = RequestMethod.GET)
	@ResponseBody
	public LatestCathecticResponse latestCathectic(HttpServletRequest request, HttpSession session) {
		LatestCathecticResponse res = new LatestCathecticResponse();
		TUser u = (TUser) session.getAttribute(Constant.SESSION_USER);
		if (u == null) {
			res.setResultCode("5");
			res.setMsg("用户登录失效，请重新登录");
			return res;
		}
		Long sumCathecticInt = 0l;

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("termCd", sys.getNextTermcd());
		// map.put("termCd", 588975);
		map.put("createUser", u.getUserId());
		map.put("isWin", "0");
		List<TCathectic> list = catecticService.selectList(map);
		if (list != null && list.size() > 0) {
			TDict dict = null;
			for (TCathectic cathectic : list) {
				cathectic.setDateTime(WebUtil.getStringDate(cathectic.getCreateTime(), Constant.DATA_HH));
				dict = sys.getDict(cathectic.getCathecticType() + "-" + cathectic.getCathecticCode());
				cathectic.setCathecticCodeStr(dict.getDictName());
				sumCathecticInt += cathectic.getCathecticInt();
			}
		}
		TCathectic c = new TCathectic();
		c.setCathecticInt(sumCathecticInt);

		res.setResultCode("0");
		res.setMsg("成功");
		res.setDataList(list);

		res.setData(c);
		/** ****两面长龙*********** */
		// Calendar cal = Calendar.getInstance();
		// int currH = cal.get(Calendar.HOUR_OF_DAY);
		// String date = dayFmarter.format(cal.getTime());
		// if (currH < 9) { // 没结果时间段
		// cal.add(Calendar.DATE, -1);
		// date = dayFmarter.format(cal.getTime());
		// }
		// map.clear();
		// map.put("dateStart", date + " 00:00:00");
		// map.put("dateEnnd", date + "23:59:59");
		// List<TDict> doubleLoong = dictService.doubleLoong(map);
		// res.setDoubleLoong(doubleLoong);
		return res;
	}

	/**
	 * 账户历史
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "cathectic_history", method = RequestMethod.GET)
	public String cathecticHistory(HttpServletRequest request, HttpServletResponse response, HttpSession session)
			throws ParseException {
		List<TCathectic> resultList = new ArrayList<TCathectic>();
		TUser u = (TUser) session.getAttribute(Constant.SESSION_USER);
		if (u == null) {
			return "login";
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("createUser", u.getUserId());
		Calendar cal = Calendar.getInstance();
		param.put("endDate", dayFmarter.format(cal.getTime()) + " 23:59:59");
		param.put("startDate", dayFmarter.format(WebUtil.getLastWeekMonday(new Date())) + " 00:00:00");
		List<TCathectic> cathecticList = catecticService.selectCatheticByDay(param);
		Map<String, String> dateMap = WebUtil.getWeekdays(new Date());
		Set<String> dateSet = dateMap.keySet();
		TCathectic ca;
		boolean hasData = false;
		for (String s : dateSet) {
			hasData = false;
			for (TCathectic c : cathecticList) {
				if (dayFmarter.format(c.getCreateTime()).equals(s)) {
					c.setDateTime(dateMap.get(s));
					resultList.add(c);
					hasData = true;
					break;
				}
			}
			if (!hasData) {
				ca = new TCathectic();
				ca.setDateTime(dateMap.get(s));
				ca.setCathecticInt(0l);
				ca.setWinAmt(0.0);
				ca.setDayCount(0);
				ca.setCreateTime(dayFmarter.parse(s));
				resultList.add(ca);
			}
		}
		Collections.sort(resultList);
		request.setAttribute("cathecticList", resultList);
		return "cathectic_history";
	}
	
	/* 两面长龙 */
	@RequestMapping(value = "flush_top", method = RequestMethod.GET)
	@ResponseBody
	public String flash_top(HttpServletRequest request, HttpSession session) {
		sys.loadTerm();
		return "两面长龙刷新完成";
	}
}
